package org.lzh.util;


import org.lzh.pojo.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器  输入一个网址，如果你登录过了(有session)就放行；如果你没登陆过，就被拦截到login
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	//private Logger logger = Logger.getLogger(LoginInterceptor.class);
    //请求之前
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		/** 拦截到用户的请求了 */
		String requestUrl = request.getRequestURL().toString();
        /** */
		System.out.println("requestUrl:"+requestUrl);
		/** 判断session是否存在用户,如果存在说明用户已经登录了,应该放行 */
		User user = (User) request.getSession().getAttribute("user_session");
		if(user!=null){
			System.out.println("requestUrl:"+requestUrl+"->被放行！");
			/** 当前请求：每个请求是否都是一个线程   */
			UserHolder.addCurrentUser(user);
			return true;
		}else{
			// 重定向 到登录页面
			response.sendRedirect(request.getContextPath()+"/");
			System.out.println("requestUrl:"+requestUrl+"->被拦截！");
			return false;
		}
	}
	
	
//请求之后
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserHolder.removeCurrentUser();		//请求完之后就要释放资源
	}


	
    
	
}
